import re
from string import *

import inspect

def lineno():
    """Returns the current line number in our program."""
    return inspect.currentframe().f_back.f_lineno
def PCLintTypeInPrevLine(line):
  words=line.split(" ")
  for word in words:
    if re.search(r"Warning",word) or re.search(r"Info",word) or re.search(r"Note",word) or re.search(r"Error",word):
	  return True
  return False
      
	  
def parseMessage(words1,words2,PCLintData):
  PCLintData["message"]=[]
  for index, word in enumerate(words1):
    if index >= 6:
      PCLintData["message"].append(word)
  for index,word in enumerate(words2):
    PCLintData["message"].append(word)
	


def parseCase1(lineList,lineIndex,PCLintData):
  words1=lineList[lineIndex-1].split(" ")
  PCLintData["filename"]=words1[0]
  PCLintData["line"]=words1[2]
  PCLintData["PCLintType"]=words1[4]  
  PCLintData["PCLintID"]=words1[5].rstrip(":")
  words2=lineList[lineIndex].split(" ")
  parseMessage(words1,words2,PCLintData)

  
def parseCase2(lineList,lineIndex,PCLintData):
  words1=lineList[lineIndex].split(" ")
  PCLintData["filename"]=words1[0]
  PCLintData["line"]=words1[2]
  PCLintData["PCLintType"]=words1[4]  
  PCLintData["PCLintID"]=words1[5].rstrip(":")
  words2=lineList[lineIndex+1].split(" ")
  parseMessage(words1,words2,PCLintData)
  
def isInList(ch,chList):
  if ch in chList:
    return True  
  else:
    return False
	
def parseMISRAID(lineList,lineIndex,PCLintData):
  PCLintData["MISRA_ID"]=[]
  words=lineList[lineIndex-1].split(" ")
  for index,word in enumerate(words):
    if re.search(r"Rule",word):
      PCLintData["MISRA_ID"].append(words[index+1])
  words=lineList[lineIndex].split(" ")
  for index,word in enumerate(words):
    if re.search(r"Rule",word):
      PCLintData["MISRA_ID"].append(words[index+1])
  if lineIndex < len(lineList)-1:
    words=lineList[lineIndex+1].split(" ")
    for index,word in enumerate(words):
      if re.search(r"Rule",word):
        PCLintData["MISRA_ID"].append(words[index+1])
  chList=['0','1','2','3','4','5','6','7','8','9','.']
  MISRAIDList=[]
  MISRAIDString=""
  for i in range(len(str(PCLintData["MISRA_ID"]))):
    if isInList(str(PCLintData["MISRA_ID"])[i],chList):
      MISRAIDString=MISRAIDString + str(PCLintData["MISRA_ID"])[i]
      if i<len(str(PCLintData["MISRA_ID"]))-1:
        if not isInList(str(PCLintData["MISRA_ID"])[i+1],chList):
          MISRAIDList.append(MISRAIDString)
          MISRAIDString=""
  PCLintData["MISRA_ID"] = MISRAIDList
	
def parsePCLintData(lineList,lineIndex,PCLintData):
  if PCLintTypeInPrevLine(lineList[lineIndex-1]):
    parseCase1(lineList,lineIndex,PCLintData)
  else:
    parseCase2(lineList,lineIndex,PCLintData)
  parseMISRAID(lineList,lineIndex,PCLintData)


def addToDb(PCLintData,conn):
  fileList=[]
  cursor = conn.cursor ()
  Query="""
    SELECT name from file
	"""
  cursor.execute (Query)
  while (1):
    row = cursor.fetchone ()
    if row == None:
      break
    fileList.append(str(row[0]))
  filename=PCLintData["filename"].replace('\\','')
  if  filename not in fileList:
    PreQuery="""
      INSERT INTO file (name,path,loc,project_id)
      VALUES (
	  """
    Query = PreQuery + "\"" + PCLintData["filename"] + "\"" +",NULL,NULL,"+"0"+ ")"
    cursor.execute (Query)
  PreQuery="""
    INSERT INTO message (text)
    VALUES (
	"""
  messageString=""
  for word in PCLintData["message"]:
    messageString=messageString + " " + word
  messageList=[]
  Query="""
    SELECT TEXT from message
  """
  cursor.execute (Query)
  while (1):
    row = cursor.fetchone ()
    if row == None:
      break
    messageList.append(str(row[0]))
  if  messageString not in messageList:
    PreQuery="""
        INSERT INTO message (TEXT)
        VALUES (
	"""
    Query=PreQuery + "\"" + messageString+ "\""+ ")"
    cursor.execute (Query)
  MISRAIDsInDBList=[]
  for MISRAID in PCLintData["MISRA_ID"]:
    Query="""
    SELECT MISRA_CODE from rule
	"""
    cursor.execute (Query)
    while (1):
      row = cursor.fetchone ()
      if row == None:
        break
      MISRAIDsInDBList.append(str(row[0]))
    if  MISRAID not in MISRAIDsInDBList:
      PreQuery="""
        INSERT INTO rule (misra_code)
        VALUES (
	  """
      Query = PreQuery + "\"" + MISRAID + "\"" + ")"
      cursor.execute (Query)
  filename=PCLintData["filename"].replace('\\','')
  Query="""
    SELECT id from file where file.NAME = 
	"""
  cursor.execute (Query + "\"" + filename+ "\"" )
  row = cursor.fetchone ()
  fileID=row[0]
  Query="""
    SELECT id from message where message.TEXT = 
	"""
  cursor.execute (Query + "\"" + messageString+ "\"" )
  row = cursor.fetchone ()
  messageID=row[0]
  for MISRAID in PCLintData["MISRA_ID"]:
    Query="""
    SELECT id from rule where rule.MISRA_CODE = 
	"""
    cursor.execute (Query + "\"" + MISRAID+ "\"" )
    row = cursor.fetchone ()
    ruleID=row[0]
    PreQuery="""
	  INSERT INTO violation (RULE_ID,LINE,MESSAGE_ID,FILE_ID,TRUE_POS,FALSE_POS,FALSE_NEG,PCLINTTYPE,PCLINTID)
	  VALUES(
	"""
    Query=PreQuery+str(ruleID)+","+PCLintData["line"]+","+str(messageID)+","+str(fileID)+","+"0"+","+"0"+","+"0"+","+"\""+PCLintData["PCLintType"]+"\""+","+str(PCLintData["PCLintID"])+")"
    cursor.execute (Query)
	
def parseFile(fp,file,conn):
  lineList=[]
  PCLintData={}
  for line in fp:
    lineList.append(strip(line))
  for lineIndex ,line in enumerate(lineList):
    if re.search(r"MISRA",line) and not re.search(r"au-misra2.lnt",line):
      parsePCLintData(lineList,lineIndex,PCLintData)
      addToDb(PCLintData,conn)
  lineList=[]

